package com.foxchen;

import ch.qos.logback.core.util.StringUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.setting.Setting;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("all")
public class MasTokenKeepAlive {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private static final Map<String,String> TOKEN_MAP = new HashMap<>();
    private static final Logger log = LoggerFactory.getLogger(MasTokenKeepAlive.class);

    static {
        // 配置文件
        String tokenConfig = new Setting("config/config.properties").get("token_config");
        log.info("files tokenConfig:{}",tokenConfig);
        // 环境变量
        String sysConfig = System.getenv("token_config");
        log.info("sysConfig tokenConfig:{}",sysConfig);
        if(sysConfig != null && !sysConfig.isEmpty()){
            tokenConfig = sysConfig;
        }
        log.info("final tokenConfig:{}",tokenConfig);
        if(StringUtil.isNullOrEmpty(tokenConfig)){
            throw new RuntimeException("config not found.");
        }

        TOKEN_MAP.clear();

        try {
            Map<String,String> dataMap = OBJECT_MAPPER.readValue(tokenConfig, new TypeReference<>() {});
            TOKEN_MAP.putAll(dataMap);
            log.info("final TOKEN_MAP:{}",TOKEN_MAP);
        } catch (JsonProcessingException e) {
            log.error("config init error", e);
        }



    }

    private static final Map<String,String> HEADER_MAP = new HashMap<>();
    static {
        HEADER_MAP.put("accept","application/json, text/javascript, */*; q=0.01");
        HEADER_MAP.put("accept-encoding","gzip, deflate, br, zstd");
        HEADER_MAP.put("accept-language","zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        HEADER_MAP.put("connection","keep-alive");
        HEADER_MAP.put("content-type","application/x-www-form-urlencoded; charset=UTF-8");
        HEADER_MAP.put("cookie","");
        HEADER_MAP.put("host","mas.10086.cn");
        HEADER_MAP.put("origin","https://mas.10086.cn");
        HEADER_MAP.put("referer","https://mas.10086.cn/ec/cmEcBill/cmEcBill.do?_=1a4bffef230a44b283dd5336e39317fd");
        HEADER_MAP.put("sec-ch-ua","\"Microsoft Edge\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"");
        HEADER_MAP.put("sec-ch-ua-mobile","?0");
        HEADER_MAP.put("sec-ch-ua-platform","\"Windows\"");
        HEADER_MAP.put("sec-fetch-dest","empty");
        HEADER_MAP.put("sec-fetch-mode","cors");
        HEADER_MAP.put("sec-fetch-site","same-origin");
        HEADER_MAP.put("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0");
        HEADER_MAP.put("x-requested-with","XMLHttpRequest");
    }

    public static void main(String[] args) throws Exception {
        if(TOKEN_MAP.isEmpty()){
            log.error("token map is empty");
            return;
        }

        while (true) {

            for (Map.Entry<String, String> entry : TOKEN_MAP.entrySet()) {
                List<Map<String, Object>> allFileTask = getAllFileTask(entry.getKey(),entry.getValue());
                log.info("name:{},token refresh ok? ==========> :{}",entry.getKey(),allFileTask != null);
            }

            TimeUnit.MINUTES.sleep(3);
        }
    }


    private static List<Map<String, Object>> getAllFileTask(String name,String cookie) throws Exception {
        Map<String, String> headerMap = new HashMap<>(HEADER_MAP);
        headerMap.put("cookie", cookie);

        Map<String,Object> formMap = new HashMap<>();
        formMap.put("centerBusinessType","01");
        formMap.put("pageIndex",1);
        formMap.put("pageSize",5);
        log.debug("name:{},request headerMap:{}",name,headerMap);
        log.debug("name:{},request formMap:{}",name,formMap);

        try(HttpResponse response = HttpUtil
                .createPost("https://mas.10086.cn/ec/downloadCenter/bill/list.ajax")
                .headerMap(headerMap, true)
                .form(formMap)
                .execute()) {
            String body = response.body();
            log.info("name:{},response:{}",name,body);
            if(StringUtil.isNullOrEmpty(body) || !(body.startsWith("{") && body.endsWith("}"))){
                return null;
            }

            Map<String, Object> responseMap = OBJECT_MAPPER.readValue(body, new TypeReference<>() {});
            return  (List<Map<String, Object>>)responseMap.get("list");
        }
    }
}
